package com.unknowpupil.alibaba.cloud.mybatis.configuration;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 处理新增和更新的基础数据填充，配合BaseEntity和MyBatisPlusConfig使用。
 *
 * @Classname: MetaHandler
 * @Author: <a> w10g </a>
 * @CreateDate: Create in 2020/1/16 11:35
 * @Description:
 * @Version: 1.0
 */
@Component
public class MetaHandler implements MetaObjectHandler {

     private static final Logger logger = LoggerFactory.getLogger(MetaHandler.class);

    /**
     * 功能描述: <br>
     * 〈 新增数据执行〉
     *
     * @auther: w10g
     * @Date: 2020/1/16 11:41
     * @since: 1.0.0
     * @Param: metaObject {@link MetaObject}
     * @return: void
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        Date date = new Date();

        logger.info(" -------------------- start insert fill 插入方法实体填充...  --------------------");
        if (metaObject.hasGetter("createdTime") && metaObject.hasGetter("updated")) {
            this.setFieldValByName("createdTime", date, metaObject);
            this.setFieldValByName("updatedTime", date, metaObject);
        }
        // 日志输出 ==================================================================
        Date created = (Date) this.getFieldValByName("createdTime", metaObject);
        Date updated = (Date) this.getFieldValByName("updatedTime", metaObject);
        if (created != null && updated != null) {
            logger.info("MyBatisPlus自动填充处理 - createdTime:{} \n updatedTime:{}", System.currentTimeMillis(), System.currentTimeMillis());
        }
    }

    /**
     * 功能描述: <br>
     * 〈 更新数据执行 MetaObject 的构造器是私有的,只提供 forObject 创建MetaObject对象〉
     *
     * @auther: w10g
     * @Date: 2020/1/16 11:40
     * @since: 1.0.0
     * @Param: metaObject {@link MetaObject}
     * @return: null
     */
    @Override
    public void updateFill(MetaObject metaObject) {

        logger.info(" -------------------- start update fill 更新方法实体填充 ...  --------------------");
        if (metaObject.hasGetter("updatedTime")) {
            this.setFieldValByName("updatedTime", new Date(), metaObject);
        }
        // 日志输出 ====================================================================================
        Date updateTime = (Date) this.getFieldValByName("updateTime", metaObject);
        if (updateTime != null) {
            logger.info("MyBatisPlus自动填充处理 - updated:{}", System.currentTimeMillis());
        }

    }
}
